package com.agileboot.attendance.domain.record.service.impl;

import com.agileboot.attendance.domain.record.db.entity.AttendanceRecord;
import com.agileboot.attendance.domain.record.db.mapper.AttendanceRecordMapper;
import com.agileboot.attendance.domain.record.dto.AttendanceRecordDTO;
import com.agileboot.attendance.domain.record.dto.AttendanceRecordImportDTO;
import com.agileboot.attendance.domain.record.dto.AttendanceRecordQueryDTO;
import com.agileboot.attendance.domain.record.dto.BatchImportDTO;
import com.agileboot.attendance.domain.record.dto.CalendarItemDTO;
import com.agileboot.attendance.domain.record.dto.CheckInDTO;
import com.agileboot.attendance.domain.record.service.IAttendanceRecordService;
import com.agileboot.attendance.domain.rule.db.entity.AttendanceRule;
import com.agileboot.attendance.domain.rule.service.IAttendanceRuleService;
import com.agileboot.common.exception.ApiException;
import com.agileboot.common.exception.error.ErrorCode;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 考勤记录Service实现类
 *
 * @author ruoyi
 */
@Service
@RequiredArgsConstructor
@Primary
public class AttendanceRecordServiceImpl extends ServiceImpl<AttendanceRecordMapper, AttendanceRecord> implements IAttendanceRecordService {

    private final IAttendanceRuleService attendanceRuleService;

    @Override
    public IPage<AttendanceRecordDTO> page(IPage<AttendanceRecord> page, AttendanceRecordQueryDTO queryDTO) {
        LambdaQueryWrapper<AttendanceRecord> wrapper = new LambdaQueryWrapper<>();

        // 员工ID查询
        if (queryDTO.getEmployeeId() != null) {
            wrapper.eq(AttendanceRecord::getEmployeeId, queryDTO.getEmployeeId());
        }

        // 员工姓名模糊查询
        if (StringUtils.hasText(queryDTO.getEmployeeName())) {
            wrapper.like(AttendanceRecord::getEmployeeName, queryDTO.getEmployeeName());
        }

        // 考勤日期查询
        if (queryDTO.getAttendanceDate() != null) {
            wrapper.eq(AttendanceRecord::getAttendanceDate, queryDTO.getAttendanceDate());
        }

        // 考勤状态查询
        if (queryDTO.getStatus() != null) {
            wrapper.eq(AttendanceRecord::getStatus, queryDTO.getStatus());
        }

        // 考勤规则ID查询
        if (queryDTO.getRuleId() != null) {
            wrapper.eq(AttendanceRecord::getRuleId, queryDTO.getRuleId());
        }

        // 日期范围查询
        if (queryDTO.getStartDate() != null && queryDTO.getEndDate() != null) {
            wrapper.between(AttendanceRecord::getAttendanceDate, queryDTO.getStartDate(), queryDTO.getEndDate());
        }

        // 按考勤日期降序排序
        wrapper.orderByDesc(AttendanceRecord::getAttendanceDate);

        // 执行分页查询
        IPage<AttendanceRecord> recordPage = this.page(page, wrapper);

        // 转换为DTO
        return recordPage.convert(record -> {
            AttendanceRecordDTO dto = new AttendanceRecordDTO();
            BeanUtils.copyProperties(record, dto);
            return dto;
        });
    }

    @Override
    public AttendanceRecordDTO getInfo(Long recordId) {
        AttendanceRecord record = this.getById(recordId);
        if (record == null) {
            return null;
        }
        AttendanceRecordDTO dto = new AttendanceRecordDTO();
        BeanUtils.copyProperties(record, dto);
        return dto;
    }

    @Override
    public boolean add(AttendanceRecordDTO recordDTO) {
        AttendanceRecord record = new AttendanceRecord();
        BeanUtils.copyProperties(recordDTO, record);
        return this.save(record);
    }

    @Override
    public boolean update(AttendanceRecordDTO recordDTO) {
        AttendanceRecord record = new AttendanceRecord();
        BeanUtils.copyProperties(recordDTO, record);
        return this.updateById(record);
    }

    @Override
    public boolean delete(Long recordId) {
        return this.removeById(recordId);
    }

    @Override
    public boolean checkIn(Long employeeId) {
        // 获取今天的考勤记录
        LocalDate today = LocalDate.now();
        LambdaQueryWrapper<AttendanceRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AttendanceRecord::getEmployeeId, employeeId)
               .eq(AttendanceRecord::getAttendanceDate, today);
        AttendanceRecord record = this.getOne(wrapper);

        if (record == null) {
            // 创建新的考勤记录
            record = new AttendanceRecord();
            record.setEmployeeId(employeeId);
            record.setAttendanceDate(today);
            record.setClockInTime(LocalDateTime.now());
            record.setStatus("1"); // 正常，对应前端AttendanceStatus.NORMAL
            return this.save(record);
        } else {
            // 更新考勤记录
            record.setClockInTime(LocalDateTime.now());
            return this.updateById(record);
        }
    }

    @Override
    public boolean checkOut(Long employeeId) {
        // 获取今天的考勤记录
        LocalDate today = LocalDate.now();
        LambdaQueryWrapper<AttendanceRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AttendanceRecord::getEmployeeId, employeeId)
               .eq(AttendanceRecord::getAttendanceDate, today);
        AttendanceRecord record = this.getOne(wrapper);

        if (record != null) {
            record.setClockOutTime(LocalDateTime.now());
            return this.updateById(record);
        }
        return false;
    }

    @Override
    public boolean advancedCheckIn(CheckInDTO checkInDTO) {
        Long employeeId = checkInDTO.getEmployeeId();
        Integer checkType = checkInDTO.getCheckType();

        // 获取今天的考勤记录
        LocalDate today = LocalDate.now();
        LambdaQueryWrapper<AttendanceRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AttendanceRecord::getEmployeeId, employeeId)
               .eq(AttendanceRecord::getAttendanceDate, today);
        AttendanceRecord record = this.getOne(wrapper);

        // 检查位置信息（如果提供了）
        if (checkInDTO.getLongitude() != null && checkInDTO.getLatitude() != null) {
            // 获取员工的考勤规则ID
            Long ruleId = 1L; // 默认规则ID，实际应从员工信息或部门配置中获取

            // 检查是否在考勤范围内
            boolean inArea = isInAttendanceArea(
                    checkInDTO.getLongitude().doubleValue(),
                    checkInDTO.getLatitude().doubleValue(),
                    ruleId
            );

            if (!inArea) {
                // 不在考勤范围内，设置为异常打卡
                if (record == null) {
                    record = new AttendanceRecord();
                    record.setEmployeeId(employeeId);
                    record.setAttendanceDate(today);
                    record.setStatus("2"); // 迟到/异常，对应前端AttendanceStatus.LATE
                    record.setRemark("位置异常打卡");
                } else {
                    record.setStatus("2"); // 迟到/异常，对应前端AttendanceStatus.LATE
                    record.setRemark(StringUtils.hasText(record.getRemark())
                            ? record.getRemark() + ";位置异常打卡"
                            : "位置异常打卡");
                }
            }
        }

        // 处理打卡类型
        LocalDateTime now = LocalDateTime.now();
        if (checkType == 0) { // 上班打卡
            if (record == null) {
                // 创建新记录
                record = new AttendanceRecord();
                record.setEmployeeId(employeeId);
                record.setAttendanceDate(today);
                record.setClockInTime(now);

                // 设置地址和照片信息
                record.setClockInAddress(checkInDTO.getAddress());
                record.setClockInPhotoUrl(checkInDTO.getPhotoUrl());

                // 如果状态未设置，默认为正常
                if (record.getStatus() == null) {
                    record.setStatus("1"); // 正常，对应前端AttendanceStatus.NORMAL
                }

                return this.save(record);
            } else {
                // 更新记录
                record.setClockInTime(now);
                record.setClockInAddress(checkInDTO.getAddress());
                record.setClockInPhotoUrl(checkInDTO.getPhotoUrl());
                return this.updateById(record);
            }
        } else if (checkType == 1) { // 下班打卡
            if (record == null) {
                // 没有上班打卡记录，创建一条异常记录
                record = new AttendanceRecord();
                record.setEmployeeId(employeeId);
                record.setAttendanceDate(today);
                record.setClockOutTime(now);
                record.setClockOutAddress(checkInDTO.getAddress());
                record.setClockOutPhotoUrl(checkInDTO.getPhotoUrl());
                record.setStatus("2"); // 迟到/异常，对应前端AttendanceStatus.LATE
                record.setRemark("无上班打卡记录");
                return this.save(record);
            } else {
                // 更新下班打卡信息
                record.setClockOutTime(now);
                record.setClockOutAddress(checkInDTO.getAddress());
                record.setClockOutPhotoUrl(checkInDTO.getPhotoUrl());
                return this.updateById(record);
            }
        }
        
        return false;
    }

    @Override
    public boolean importRecords(List<AttendanceRecordDTO> recordList) {
        if (recordList == null || recordList.isEmpty()) {
            return false;
        }

        List<AttendanceRecord> entities = recordList.stream().map(dto -> {
            AttendanceRecord entity = new AttendanceRecord();
            BeanUtils.copyProperties(dto, entity);
            return entity;
        }).collect(Collectors.toList());

        return this.saveBatch(entities);
    }

    @Override
    public List<AttendanceRecordDTO> export(AttendanceRecordQueryDTO queryDTO) {
        // 设置不分页
        Page<AttendanceRecord> page = new Page<>(1, Integer.MAX_VALUE);
        IPage<AttendanceRecordDTO> pageResult = this.page(page, queryDTO);
        return pageResult.getRecords();
    }

    @Override
    public Map<String, Object> getMonthlyStatistics(Long employeeId, String yearMonth) {
        // 解析年月
        YearMonth ym = YearMonth.parse(yearMonth, DateTimeFormatter.ofPattern("yyyy-MM"));
        LocalDate startDate = ym.atDay(1);
        LocalDate endDate = ym.atEndOfMonth();

        // 查询该月所有考勤记录
        LambdaQueryWrapper<AttendanceRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AttendanceRecord::getEmployeeId, employeeId)
               .between(AttendanceRecord::getAttendanceDate, startDate, endDate);
        List<AttendanceRecord> records = this.list(wrapper);

        // 统计数据
        int totalDays = ym.lengthOfMonth();
        int attendanceDays = 0;
        int lateDays = 0;
        int earlyDays = 0;
        int absentDays = 0;
        int normalDays = 0;

        // 假设迟到、早退、缺勤的判断逻辑
        for (AttendanceRecord record : records) {
            if ("0".equals(record.getStatus())) {
                normalDays++;
            } else if ("1".equals(record.getStatus())) {
                if (record.getClockInTime() == null && record.getClockOutTime() == null) {
                    absentDays++;
                } else if (record.getClockInTime() != null && record.getClockOutTime() != null) {
                    // 假设有规则判断迟到和早退
                    // 这里只是示例，实际需要根据规则判断
                    LocalTime standardStartTime = LocalTime.of(9, 0);
                    LocalTime standardEndTime = LocalTime.of(18, 0);

                    if (record.getClockInTime().toLocalTime().isAfter(standardStartTime)) {
                        lateDays++;
                    }

                    if (record.getClockOutTime().toLocalTime().isBefore(standardEndTime)) {
                        earlyDays++;
                    }
                }
            }

            if (record.getClockInTime() != null || record.getClockOutTime() != null) {
                attendanceDays++;
            }
        }

        // 构建统计结果
        Map<String, Object> result = new HashMap<>();
        result.put("employeeId", employeeId);
        result.put("yearMonth", yearMonth);
        result.put("totalDays", totalDays);
        result.put("attendanceDays", attendanceDays);
        result.put("normalDays", normalDays);
        result.put("lateDays", lateDays);
        result.put("earlyDays", earlyDays);
        result.put("absentDays", absentDays);
        result.put("rows", records);

        return result;
    }

    @Override
    public Map<String, Object> getDeptMonthlyStatistics(Long deptId, String yearMonth) {
        // 此处需要先获取部门下所有员工ID
        List<Long> employeeIds = new ArrayList<>();
        // TODO: 从用户服务获取部门下所有员工ID

        // 汇总每个员工的统计数据
        List<Map<String, Object>> employeeStats = new ArrayList<>();
        for (Long employeeId : employeeIds) {
            Map<String, Object> stat = getMonthlyStatistics(employeeId, yearMonth);
            employeeStats.add(stat);
        }

        // 计算部门汇总数据
        int totalEmployees = employeeIds.size();
        int totalAttendanceDays = 0;
        int totalNormalDays = 0;
        int totalLateDays = 0;
        int totalEarlyDays = 0;
        int totalAbsentDays = 0;

        for (Map<String, Object> stat : employeeStats) {
            totalAttendanceDays += (int) stat.get("attendanceDays");
            totalNormalDays += (int) stat.get("normalDays");
            totalLateDays += (int) stat.get("lateDays");
            totalEarlyDays += (int) stat.get("earlyDays");
            totalAbsentDays += (int) stat.get("absentDays");
        }

        // 构建部门统计结果
        Map<String, Object> result = new HashMap<>();
        result.put("deptId", deptId);
        result.put("yearMonth", yearMonth);
        result.put("totalEmployees", totalEmployees);
        result.put("totalAttendanceDays", totalAttendanceDays);
        result.put("totalNormalDays", totalNormalDays);
        result.put("totalLateDays", totalLateDays);
        result.put("totalEarlyDays", totalEarlyDays);
        result.put("totalAbsentDays", totalAbsentDays);
        result.put("employeeStats", employeeStats);

        return result;
    }

    @Override
    public boolean isInAttendanceArea(Double longitude, Double latitude, Long ruleId) {
        // 获取考勤规则
        AttendanceRule rule = attendanceRuleService.getById(ruleId);
        if (rule == null) {
            return false;
        }

        // 获取考勤地点范围（经度、纬度、半径）
        BigDecimal centerLongitude = rule.getLongitude();
        BigDecimal centerLatitude = rule.getLatitude();
        BigDecimal radius = rule.getRadius();

        if (centerLongitude == null || centerLatitude == null || radius == null) {
            // 未设置考勤范围，默认在范围内
            return true;
        }

        // 计算距离（使用简化的球面距离计算）
        double distance = calculateDistance(longitude, latitude,
                centerLongitude.doubleValue(), centerLatitude.doubleValue());

        // 判断是否在半径范围内
        return distance <= radius.doubleValue();
    }

    @Override
    public String getEmployeeDailyStatus(Long employeeId, LocalDate date) {
        LambdaQueryWrapper<AttendanceRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AttendanceRecord::getEmployeeId, employeeId)
               .eq(AttendanceRecord::getAttendanceDate, date);
        AttendanceRecord record = this.getOne(wrapper);

        if (record == null) {
            return "未打卡";
        }

        if ("0".equals(record.getStatus())) {
            return "正常";
        } else if ("1".equals(record.getStatus())) {
            return "异常";
        } else if ("2".equals(record.getStatus())) {
            return "请假";
        } else if ("3".equals(record.getStatus())) {
            return "出差";
        } else {
            return "未知";
        }
    }

    /**
     * 计算两点之间的距离（米）
     * 使用球面距离公式（Haversine公式）计算
     */
    private double calculateDistance(double lon1, double lat1, double lon2, double lat2) {
        final double EARTH_RADIUS = 6371000; // 地球半径，单位米

        double radLat1 = Math.toRadians(lat1);
        double radLat2 = Math.toRadians(lat2);
        double a = radLat1 - radLat2;
        double b = Math.toRadians(lon1) - Math.toRadians(lon2);

        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
               Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;

        return s;
    }

    /**
     * 获取员工月度考勤日历数据
     *
     * @param employeeId 员工ID
     * @param yearMonth 年月（格式：yyyy-MM）
     * @return 日历数据列表
     */
    @Override
    public List<CalendarItemDTO> getMonthlyCalendar(Long employeeId, String yearMonth) {
        // 解析年月
        YearMonth ym = YearMonth.parse(yearMonth, DateTimeFormatter.ofPattern("yyyy-MM"));
        LocalDate startDate = ym.atDay(1);
        LocalDate endDate = ym.atEndOfMonth();

        // 获取该月所有考勤记录
        LambdaQueryWrapper<AttendanceRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AttendanceRecord::getEmployeeId, employeeId)
               .between(AttendanceRecord::getAttendanceDate, startDate, endDate);
        List<AttendanceRecord> records = this.list(wrapper);

        // 将考勤记录转换为Map，以日期为键
        Map<LocalDate, AttendanceRecord> recordMap = records.stream()
                .collect(Collectors.toMap(AttendanceRecord::getAttendanceDate, record -> record));

        // 生成月份的所有日期
        List<CalendarItemDTO> calendarItems = new ArrayList<>();
        for (int i = 1; i <= ym.lengthOfMonth(); i++) {
            LocalDate date = ym.atDay(i);
            CalendarItemDTO item = new CalendarItemDTO();
            item.setDate(date);

            // 判断是否是周末
            boolean isWeekend = date.getDayOfWeek().getValue() >= 6; // 周六或周日

            if (isWeekend) {
                // 周末
                item.setStatus("4"); // 休息日
                item.setStatusText("休息日");
            } else {
                // 如果有考勤记录，使用记录的状态
                if (recordMap.containsKey(date)) {
                    AttendanceRecord record = recordMap.get(date);
                    item.setStatus(record.getStatus());
                    item.setClockInTime(record.getClockInTime());
                    item.setClockOutTime(record.getClockOutTime());
                    item.setDuration(record.getDuration());
                    item.setRemark(record.getRemark());

                    // 根据状态设置状态文本
                    if ("0".equals(record.getStatus())) {
                        item.setStatusText("正常");
                    } else if ("1".equals(record.getStatus())) {
                        item.setStatusText("异常");
                    } else if ("2".equals(record.getStatus())) {
                        item.setStatusText("请假");
                    } else if ("3".equals(record.getStatus())) {
                        item.setStatusText("出差");
                    } else {
                        item.setStatusText("未知");
                    }
                } else {
                    // 工作日但无考勤记录
                    if (date.isEqual(LocalDate.now()) || date.isAfter(LocalDate.now())) {
                        // 今天或未来日期
                        item.setStatus(null);
                        item.setStatusText("未打卡");
                    } else {
                        // 过去日期
                        item.setStatus("4"); // 缺勤，对应前端AttendanceStatus.ABSENT
                        item.setStatusText("缺勤");
                    }
                }
            }

            calendarItems.add(item);
        }

        return calendarItems;
    }

    /**
     * 批量导入考勤记录
     *
     * @param batchImportDTO 批量导入参数
     * @return 导入结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> batchImport(BatchImportDTO batchImportDTO) {
        List<AttendanceRecordImportDTO> importList = batchImportDTO.getRecords();

        // 导入结果统计
        int totalCount = importList.size();
        int successCount = 0;
        int failCount = 0;
        List<String> errorMessages = new ArrayList<>();

        // 批量导入记录
        List<AttendanceRecord> recordsToSave = new ArrayList<>();

        for (int i = 0; i < importList.size(); i++) {
            AttendanceRecordImportDTO importDTO = importList.get(i);
            try {
                AttendanceRecord record = validateAndConvert(importDTO);

                // 设置批次信息
                record.setCreatorId(0L); // 设置为系统用户ID
                record.setRemark(StringUtils.hasText(record.getRemark()) ?
                        record.getRemark() + ";来源:" + batchImportDTO.getSource() + ";操作人:" + batchImportDTO.getOperator() :
                        "来源:" + batchImportDTO.getSource() + ";操作人:" + batchImportDTO.getOperator());

                recordsToSave.add(record);
                successCount++;
            } catch (Exception e) {
                failCount++;
                errorMessages.add("第" + (i + 1) + "条记录导入失败: " + e.getMessage());
            }
        }

        // 批量保存
        if (!recordsToSave.isEmpty()) {
            this.saveBatch(recordsToSave);
        }

        // 返回导入结果
        Map<String, Object> result = new HashMap<>();
        result.put("batchNo", batchImportDTO.getBatchNo());
        result.put("totalCount", totalCount);
        result.put("successCount", successCount);
        result.put("failCount", failCount);
        result.put("errorMessages", errorMessages);

        return result;
    }

    /**
     * 从文件导入考勤记录
     *
     * @param filePath 文件路径
     * @param source 数据来源
     * @param operator 操作人
     * @return 导入结果
     */
    @Override
    public Map<String, Object> importFromFile(String filePath, String source, String operator) {
        // 生成批次号
        String batchNo = generateBatchNo();

        // 根据文件类型调用不同的解析方法
        List<AttendanceRecordImportDTO> importList = new ArrayList<>();

        if (filePath.endsWith(".xlsx") || filePath.endsWith(".xls")) {
            // Excel文件解析
            importList = parseExcelFile(filePath);
        } else if (filePath.endsWith(".csv")) {
            // CSV文件解析
            importList = parseCsvFile(filePath);
        } else if (filePath.endsWith(".txt")) {
            // 文本文件解析
            importList = parseTextFile(filePath);
        } else {
            throw new ApiException(ErrorCode.Business.COMMON_UNSUPPORTED_OPERATION, "不支持的文件类型");
        }

        // 构建批量导入DTO
        BatchImportDTO batchImportDTO = new BatchImportDTO();
        batchImportDTO.setBatchNo(batchNo);
        batchImportDTO.setSource(source);
        batchImportDTO.setOperator(operator);
        batchImportDTO.setRecords(importList);

        // 执行批量导入
        return batchImport(batchImportDTO);
    }

    /**
     * 将导入DTO转换为考勤记录实体并进行验证
     *
     * @param importDTO 导入数据
     * @return 考勤记录实体
     */
    @Override
    public AttendanceRecord validateAndConvert(AttendanceRecordImportDTO importDTO) {
        if (importDTO == null) {
            throw new ApiException(ErrorCode.Business.COMMON_OBJECT_NOT_FOUND, "导入数据");
        }

        // 验证必填字段
        if (importDTO.getEmployeeCode() == null) {
            throw new ApiException(ErrorCode.Business.COMMON_UNSUPPORTED_OPERATION, "员工编号不能为空");
        }
        if (importDTO.getAttendanceDate() == null) {
            throw new ApiException(ErrorCode.Business.COMMON_UNSUPPORTED_OPERATION, "考勤日期不能为空");
        }

        // 查找员工ID
        Long employeeId = getEmployeeIdByCode(importDTO.getEmployeeCode());
        if (employeeId == null) {
            throw new ApiException(ErrorCode.Business.COMMON_UNSUPPORTED_OPERATION, "员工不存在: " + importDTO.getEmployeeCode());
        }

        // 构建考勤记录
        AttendanceRecord record = new AttendanceRecord();
        record.setEmployeeId(employeeId);
        record.setEmployeeName(importDTO.getEmployeeName());
        record.setAttendanceDate(importDTO.getAttendanceDate());
        record.setClockInTime(importDTO.getClockInTime());
        record.setClockInAddress(importDTO.getClockInAddress());
        record.setClockOutTime(importDTO.getClockOutTime());
        record.setClockOutAddress(importDTO.getClockOutAddress());
        record.setRemark(importDTO.getRemark());

        // 设置状态，如果导入数据中有状态则使用导入的状态，否则根据打卡情况判断
        if (importDTO.getStatus() != null) {
            // 使用导入的状态
            record.setStatus(importDTO.getStatus());
        } else {
            // 根据打卡情况判断状态
            LocalDateTime clockInTime = importDTO.getClockInTime();
            LocalDateTime clockOutTime = importDTO.getClockOutTime();

            if (clockInTime == null && clockOutTime == null) {
                throw new ApiException(ErrorCode.Business.COMMON_UNSUPPORTED_OPERATION, "打卡时间不能同时为空");
            }

            if (clockInTime == null) {
                // 只有下班打卡，标记为异常
                record.setStatus("2"); // 迟到/异常，对应前端AttendanceStatus.LATE
            } else if (clockOutTime == null) {
                // 只有上班打卡，标记为异常
                record.setStatus("2"); // 迟到/异常，对应前端AttendanceStatus.LATE
            } else {
                // 计算标准打卡时间
                LocalTime standardStartTime = LocalTime.of(9, 0); // 标准上班时间
                LocalTime standardEndTime = LocalTime.of(18, 0);  // 标准下班时间

                // 检查是否迟到或早退
                if (clockInTime.toLocalTime().isAfter(standardStartTime)) {
                    record.setStatus("2"); // 迟到，对应前端AttendanceStatus.LATE
                } else if (clockOutTime.toLocalTime().isBefore(standardEndTime)) {
                    record.setStatus("3"); // 早退，对应前端AttendanceStatus.EARLY_LEAVE
                } else {
                    record.setStatus("1"); // 正常，对应前端AttendanceStatus.NORMAL
                }
            }
        }

        return record;
    }

    /**
     * 生成批次号
     */
    private String generateBatchNo() {
        // 简单实现：日期时间+随机数
        return "BATCH_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) +
                "_" + (int)(Math.random() * 1000);
    }

    /**
     * 根据员工编号获取员工ID
     */
    private Long getEmployeeIdByCode(String employeeCode) {
        // TODO: 实际实现应调用员工服务查询
        // 此处简单模拟，假设编号即ID
        try {
            return Long.parseLong(employeeCode);
        } catch (NumberFormatException e) {
            // 如果不是数字，需要通过员工服务查询
            // 此处模拟返回null表示未找到
            return null;
        }
    }

    /**
     * 解析Excel文件
     */
    private List<AttendanceRecordImportDTO> parseExcelFile(String filePath) {
        // TODO: 实现Excel文件解析
        // 此处简单返回空列表
        return new ArrayList<>();
    }

    /**
     * 解析CSV文件
     */
    private List<AttendanceRecordImportDTO> parseCsvFile(String filePath) {
        // TODO: 实现CSV文件解析
        // 此处简单返回空列表
        return new ArrayList<>();
    }

    /**
     * 解析文本文件
     */
    private List<AttendanceRecordImportDTO> parseTextFile(String filePath) {
        // TODO: 实现文本文件解析
        // 此处简单返回空列表
        return new ArrayList<>();
    }
}
